package aptech.ad02.database;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class MySQLiteHelper extends SQLiteOpenHelper {

	public static String DB_PATH = "/data/data/com.example.danangtravel/databases/";
	// private String DB_PATH =
	// mycontext.getApplicationContext().getPackageName()+"/databases/";

	public static final String DATABASE_NAME = "DaNangTravel.sqlite";
	private static final int DATABASE_VERSION = 1;

	private SQLiteDatabase myDataBase;
	private final Context myContext;

	public MySQLiteHelper(Context context) throws IOException {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		this.myContext = context;
		boolean dbexist = checkDataBase();
		if (dbexist) {
			System.out.println("Database exists");
			openDataBase();
		} else {
			System.out.println("Database doesn't exist");
			createDataBase();
		}
	}

	public void createDataBase() throws IOException {
		boolean dbExist = checkDataBase();
		if (dbExist) {
			System.out.println("Database exists.");
			return;
		} else {
			this.getReadableDatabase();
			try {
				copyDataBase();
			} catch (IOException e) {

				throw new Error("Error copying database");

			}
		}
	}

	private boolean checkDataBase() {
		boolean checkdb = false;
		try {
			String myPath = DB_PATH + DATABASE_NAME;
			File dbfile = new File(myPath);
			checkdb = dbfile.exists();
		} catch (SQLiteException e) {
			System.out.println("Database doesn't exist");
		}

		return checkdb;
	}

	private void copyDataBase() throws IOException {
		InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
		String outFileName = DB_PATH + DATABASE_NAME;
		OutputStream myOutput = new FileOutputStream(outFileName);
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}
		myOutput.flush();
		myOutput.close();
		myInput.close();
	}

	public void openDataBase() throws SQLException {
		String myPath = DB_PATH + DATABASE_NAME;
		myDataBase = SQLiteDatabase.openDatabase(myPath, null,
				SQLiteDatabase.OPEN_READWRITE);

	}

	@Override
	public synchronized void close() {
		if (myDataBase != null)
			myDataBase.close();
		super.close();
	}

	@Override
	public void onCreate(SQLiteDatabase database) {
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// Log.w(MySQLiteHelper.class.getName(),
		// "Upgrading database from version " + oldVersion + " to "
		// + newVersion + ", which will destroy all old data");
	}

}
